package com.xyyhome.web.love.controller;

import com.xyyhome.web.love.domain.YLDynamic;
import com.xyyhome.web.love.domain.YLDynamicComment;
import com.xyyhome.web.love.domain.YLDynamicCommentRepository;
import com.xyyhome.web.love.domain.YLDynamicRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

/**
 * 模块基础控制器
 * Created by ty850 on 2017/5/21.
 */
@Controller
@RequestMapping("/love")
public class YLIndexController extends YLBaseController {

    @Autowired
    private YLDynamicRepository ylDynamicRepository;

    @Autowired
    private YLDynamicCommentRepository yLDynamicCommentRepository;


    @RequestMapping
    public String index(ModelMap map) {
        List<YLDynamic> all = ylDynamicRepository.findAll();


        HashMap<String, List<YLDynamicComment>> commentsMap = new HashMap<>();

        // 获取所有评论的id
        LinkedList<String> ids = new LinkedList<>();
        for (YLDynamic dynamic : all) {
            ids.add(dynamic.getYldId());
        }

        // 获取每一条动态的评论
        List<YLDynamicComment> comments = yLDynamicCommentRepository.findByYldcDynamicIdIn(ids);

        // 遍历评论，只处理一级
        for (YLDynamicComment comment : comments) {
            if (!StringUtils.isEmpty(comment.getYldcReplyUserId()))
                continue;

            List<YLDynamicComment> commentsMapComments = commentsMap.get(comment.getYldcDynamicId());
            if (commentsMapComments == null) {
                commentsMapComments = new LinkedList<>();
                commentsMap.put(comment.getYldcDynamicId(), commentsMapComments);
            }
            commentsMapComments.add(comment);
        }


        map.put("all",all);
        map.put("commentsMap",commentsMap);
        return toPage("index");
    }

    @RequestMapping("/add")
    public String add(ModelMap map, String content) {
        if (StringUtils.isEmpty(content))
            map.put("err", "请输入内容");
        else {
            YLDynamic ylDynamic = new YLDynamic();
            ylDynamic.setYldContent(content);
            ylDynamic.setYldUserId("哈哈");
            ylDynamicRepository.save(ylDynamic);
            ylDynamicRepository.flush();
        }
        return index(map);
    }

}
